
// 引入mongoose
const mongoose = require("mongoose");

// 获取全部秒杀
const get = async ({ curPage, eachPage }) => {
    const secondKillModel = mongoose.model("secondKill")
    //将数据转换为number
    curPage = ~~curPage;
    eachPage = ~~eachPage;
    const data = {
        total: 0,
        maxPage: 0,
        rows: [],
    }
    // 通过model方法获取模型 一个参数获取 三个参数创建
    // 获取当前model映射的集合里面存在的文档总数
    data.total = await secondKillModel.countDocuments();
    data.maxPage = Math.ceil(data.total / eachPage);
    // 跳过数据条数
    const skipNum = (curPage - 1) * eachPage;
    // 查询所有数据，并跳过skipnum条，查eachpage条并执行
    data.rows = await secondKillModel.find().populate("CommId").skip(skipNum).limit(eachPage).exec();
    return data;
}

// 新增秒杀
const add = async ({ CommId, Sale, Time, count }) => {
    const secondKillModel = mongoose.model("secondKill")
    const commsModel = mongoose.model("comms");
    const data = await secondKillModel.create({ Sale, Time, CommId, limit: count });
    await commsModel.findByIdAndUpdate({ _id: CommId }, { isAttend: true })
    return data
}

// 修改秒杀
// 更新订单状态
const change = async ({ Sale, Time, count, isAttend, _id, CommId }) => {
    console.log("xgrouter");
    const secondKillModel = mongoose.model("secondKill")
    const commsModel = mongoose.model("comms");
    const data = await secondKillModel.findByIdAndUpdate({ _id }, { Sale, Time, count, });
    commsModel.findByIdAndUpdate({ _id: CommId }, { isAttend })
    if (data) {
        return true;
    }
    return false;
}

//获取某一条秒杀商品
const getOne = async ({ _id }) => {
    console.log("api", { _id });
    const secondKillModel = mongoose.model("secondKill")
    const data = await secondKillModel.findOne({ _id });
    return data
}

//删除秒杀商品
const deleteID = async ({ _id }) => {
    console.log({ _id });
    const secondKillModel = mongoose.model("secondKill")
    const commsModel = mongoose.model("comms");
    const data = await commsModel.findOne({ _id })
    await secondKillModel.findOneAndDelete({ CommId: data._id });
    return await commsModel.findOneAndUpdate({ _id }, { isAttend: false })
}

const getComm = async ({ _id }) => {
    console.log("api", { _id });
    const secondKillModel = mongoose.model("secondKill")
    const data = await secondKillModel.findOne({ CommId: _id });
    return data
}


module.exports = { get, add, change, deleteID, getOne, getComm }


